import React from "react"
import ReactDOM from "react-dom"
import classNames from 'classnames'
require('./Toast.less')

class Toast extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
        }
    }
    makeContent() {
        const props = this.props
        let icon, cls

        //为了适配新版的字体重置
        if(props.type === "new") {
            cls = "lux-new"
        }

        if(props.mode === "warn"){
            icon = "iconfont icon-iconfontjinggao"
        }else if (props.mode === "success"){
            icon = "iconfont icon-duigouzhuanhuan"
        }else if (props.mode === "error"){
            icon = "iconfont icon-cha"
        }else if (props.mode === "loading"){
            icon = "weui-loading weui-icon_toast"
        }
        return (
            <div>
                <div className="weui-mask_transparent" onClick={this.props.onClose}></div>
                <div className={classNames("weui-toast", cls)}>
                    <i className={icon}></i>
                    <p className="weui-toast__content">{props.content || ""}</p>
                </div>
            </div>
        )
    }
    render() {
        const props = this.props
        let content = this.makeContent()
        return (
            <div className="Dialog">
                {content}
            </div>
        )
    }
}
module.exports = Toast
function operate(mode, props) {
    const div = document.createElement('div')
    let closed=false
    document.body.appendChild(div)   
    function close() {
        if(!closed){
            ReactDOM.unmountComponentAtNode(div)
            document.body.removeChild(div)
            closed = true
        }
    }
    ReactDOM.render(<Toast onClose={close} mode={mode} {...props} />,div)
    // 如果 props 里没有延迟时间，两秒后 Toast 自动移除
    // 此外，点击蒙层立即关闭 Toast
    let duration = 2000
    if(props.duration){
        duration = props.duration
    }
    setTimeout(close, duration)
}
Toast.warn = (props)=> {
    return operate("warn", props)
}
Toast.success = (props)=> {
    return operate("success", props)
}
Toast.error = (props)=> {
    return operate("error", props)
}
Toast.loading = (props)=> {
    return operate("loading", props)
}